package com.starbaba.core.web.taglib.component;

import java.io.Writer;

import org.apache.struts2.components.Component;

import com.starbaba.core.hibernate.Page;
import com.opensymphony.xwork2.util.ValueStack;

public class WebPageComponent extends Component {

	public static final String DEFAULT_PAGE_NUM_SHOW = "10";

	private Page page;
	private String numb;

	public String getNumb() {
		return numb;
	}

	public void setNumb(String numb) {
		this.numb = numb;
	}

	public WebPageComponent(ValueStack stack) {
		super(stack);
	}

	@Override
	public boolean start(Writer writer) {
		boolean result = super.start(writer);
		try {
			StringBuilder str = new StringBuilder();
			int total = page.getTotalCount();
			int pageNo = page.getPageNo();// 当前页数
			int pageSize = page.getPageSize();
			int groupNum = 8;// 8页一组
			// 计算一共分多少页
			int group = (total - 1) / pageSize + 1;
			// 如果只有一页
			if (total < pageSize) {
				str
						.append("<a href='#'>首页</a> | <a class='curr' href='#'>1</a> | <a href='#'>末页</a>");
			}
			// 如果大于一页
			else {
				// 当前第几组
				int cgroup = (pageNo - 1) / groupNum + 1;

				// 10个为一组显示
				str.append("<a href='javascript:doQuery(1," + pageSize
						+ ",0,0);'>");
				str.append("首页</a> | ");

				int minNum = (cgroup - 1) * groupNum + 1;
				int maxNum = cgroup * groupNum;
				int num = Integer.parseInt(numb);

				// 当选择页数为该组最前一页或最后一页时，向页标向后移动4位或向前移动4位
				if (num != 0 && pageNo != 1) {
					minNum += num;
					if (minNum < 0) {
						minNum = 1;
					}
					if (group > groupNum) {
						int maxTmp = maxNum;
						maxTmp += num;
						if (maxTmp < groupNum) {
							maxNum = groupNum;
						} else {
							maxNum += num;
						}
					} else {
						maxNum += num;
					}
				}

				int currGroupNum = 0;
				for (int i = 0; i < 7; i++) {
					currGroupNum = maxNum - minNum;
					if (currGroupNum < 7) {
						if (minNum != 1) {
							minNum--;
						}
					} else {
						break;
					}
				}

				for (int i = minNum; i <= total && i <= maxNum && i <= group; i++) {
					if (pageNo == i) { // 当前页要加粗显示
						str.append("<a class='curr' href='javascript:doQuery("
								+ i + "," + pageSize + "," + minNum + ","
								+ maxNum + ");'>");
						str.append(i + "</a> | ");
					} else {
						str.append("<a href='javascript:doQuery(" + i + ","
								+ pageSize + "," + minNum + "," + maxNum
								+ ");'>");
						str.append(i + "</a> | ");
					}
				}
				str.append("<a href='javascript:doQuery(" + group + ","
						+ pageSize + ",0,0);'>");
				str.append("末页</a>");
			}

			writer.write(str.toString());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}
}
